package struct;

/**
 * a / b 向上取整 (a + b - 1) / b
 */
public class BitSet {

    private static final int ONE_BUCKET_SIZE = 32;

    private final int[] SET;

    public static void main(String[] args) {
        System.out.println(32 & ~0);

        BitSet bitSet = new BitSet(100);

        bitSet.add(5);
        bitSet.add(8);
        bitSet.reverse(5);
        bitSet.reverse(50);
        System.out.println(bitSet.contains(5));

    }

    public BitSet(int size) {
        SET = new int[(size + ONE_BUCKET_SIZE - 1) / ONE_BUCKET_SIZE];
    }

    private int getIndex(int num) {
        return num / ONE_BUCKET_SIZE;
    }

    private int getValue(int num) {
        return 1 << (num % ONE_BUCKET_SIZE);
    }

    public void add(int num) {
        SET[getIndex(num)] |= getValue(num);
    }

    public void remove(int num) {
        SET[getIndex(num)] &= ~getValue(num);
    }

    /**
     * 有则删除、无则加入
     * @param num 数值
     */
    public void reverse(int num) {
        SET[getIndex(num)] ^= getValue(num);
    }

    public boolean contains(int num) {
        return ((SET[getIndex(num)] >> (num % ONE_BUCKET_SIZE)) & 1) == 1;
    }

}
